<template>
  <basic-container>
    <avue-crud :option="option" :search.sync="search" :table-loading="loading" :data="data" :page.sync="page"
      :permission="permissionList" :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate"
      @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @sort-change="sortChange" @on-load="onLoad">
      <template slot="menuLeft">
        <!-- <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.shop_refund_delete"
          @click="handleDelete">删 除
        </el-button> -->
      </template>
      <template slot="menuRight">
        <el-button type="success" size="small" plain icon="el-icon-upload2" v-if="permission.shop_refund_import"
          @click="handleImport">导入
        </el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" v-if="permission.shop_refund_export"
          @click="handleExport">导出
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
            <el-button   type="primary" size="small"
            @click="handlExamine(row)">审核</el-button>
            <el-button  type="primary" size="small" @click="handleDetail(row)">详情</el-button>
      </template>

    </avue-crud>
    <el-dialog title="数据导入" append-to-body :visible.sync="excelBox" width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <div class="curd-foter">
      <div class="redFontBox">未审核订单：<span class="redFont">{{countData.unapprovedCount }}</span> 条</div>
      <div class="redFontBox">未审核总金额：<span class="redFont">{{countData.unapprovedTotalPrice }}</span> 元</div>
    </div>

    
    <!-- 退款审核 -->
    <el-dialog
      title="退款审核"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="examineVisible"
      v-if="examineVisible"
      :before-close="examineHandleClose"
      ref="terDialog"
    > 
      <el-row :gutter="24" style="font-size: 18px;">
        <el-col :span="8">
          <span>退款单号:{{ examineData.shopRefundNo }}</span>
        </el-col>
        <el-col :span="8">
          <span>订单号:{{ examineData.shopOrderNo }}</span>
        </el-col>

        <el-col :span="8">
          <span>退款金额：{{ examineData.shopRefundTotal }}</span>
        </el-col>
    
        <el-col :span="24">
          <div style="padding-bottom:8px;">备注内容: </div>
          <el-input type="textarea" :rows="5" v-model="examineData.shopExRemarks" ></el-input>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-preventClick @click="handleReject">驳回</el-button>
        <el-button type="primary" v-preventClick @click="handleRefund">通过</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>


<script>
import { ShopRefundUnapprovedList, getDetail, add, update, remove,exportRefundUnapproved,refundStatistics } from "@/api/rb-oem/shopRefund/shop_refund";
import { mapGetters } from "vuex";
import { downloadFileExcel } from "@/util/util";
import { getToken } from '@/util/auth';
export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      countData: [],
      option: {
       height: "calc(50vh - 50px)",
        calcHeight: 30,
        menuWidth:180,
        menuAlign:'right',
        searchLabelWidth: 120,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        delBtn:false,
        selection: true,
        searchMenuSpan: 24,
        columnBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            hide: true,
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: "退款编号",
            prop: "shopRefundNo",
            type: "input",
            minWidth:200
            //sortable: true,
          },
          {
            label: "订单编号",
            prop: "shopOrderNo", 
            search: true,
            type: "input",
            //sortable: true,
            minWidth:200
          },
          {
            label: "流水号",
            prop: "shopSerialNo",
            type: "input",
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            span:12,
            //sortable: true,
            search: true,
            rules: [{
              required: true,
              message: "请输入交易流水号",
              trigger: "blur"
            }],
            minWidth:200
          },
          {
            label: "退款人",
            prop: "serviceName",
            type: "input",
            //sortable: true,
            search: true,
            span:12,
            hide:false,
          },
          {
            label: "产品分类",
            prop: "shopClassNo",
            type: "select",
            props: {
              label: 'shopClassName',
              value: 'shopClassNo',
            },
            dicUrl:'/api/rb-oem/oem/shopType/shop_type/listClassName',
            //sortable: true,
            span:12,
          },
          {
            label: "产品类型",
            prop: "shopTypeNo",
            type: "select",
            props: {
              label: 'shopTypeName',
              value: 'shopTypeNo',
            },
            dicUrl:'/api/rb-oem/oem/shopType/shop_type/listTypeName',
            //sortable: true,
            span:12,
          },
          {
            label: "产品型号",
            prop: "shopModelNo",
            type: "select",
            //sortable: true,
            props: {
              label: 'shopModelName',
              value: 'shopModelNo',
            },
            dicUrl:'/api/rb-oem/oem/shopModel/shop_model/modelNameNoList',
            span:12,
            overHidden:true,
            minWidth:100
          },
          {
            label: "销售单价",
            prop: "shopModelPrice",
            type: "input",
            span:12,
            //sortable: true,
            addDisplay: true,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: "订单数量",
            prop: "shopOrderNumber",
            type: "input",
            span:12,
            //sortable: true,
            addDisplay: true,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: "订单总额",
            prop: "shopRefundTotal",
            type: "input",
            span:12,
            //sortable: true,
            addDisplay: false,
          },
          {
            label: "订单日期",
            prop: "createTime",
            type: "datetime",
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            minWidth:150
           
          },
          {
            label: "物流公司",
            prop: "shopLogisticsCompany",
            type: "input",
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            span:12,
            hide:true,
          },
          {
            label: "物流单号",
            prop: "shopLogisticsNo",
            type: "input",
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            span:12,
            hide:true,
          },
          {
            label: "配送方式",
            prop: "shopDeliveryMethod",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=shop_delivery_method",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            //sortable: true,
            span:12,
          },
          {
            label: "服务商编号",
            prop: "serviceNo",
            type: "input",
            //sortable: true,
             search: true,
            span:12,
            hide:true,
            minWidth:180,
            overHidden:true
          },

          {
            label: "收货人",
            prop: "shopConsignee",
            type: "input",
            //sortable: true,
            search: true,
            span:12,
            hide:true,
          },
          {
            label: "收货人联系方式",
            prop: "shopConsigneePhone",
            type: "input",
            //sortable: true,
            search: true,
            span:12,
            hide:true,
          },
          {
            label: "收货地址",
            prop: "shopConsigneeAddress",
            type: "input",
            //sortable: true,
            span:12,
            hide:true,
            minWidth:150,
            overHidden:true
          },
          {
            label: "退款状态",
            prop: "shopOrderStatus",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=shop_refund_status",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: false,
            //sortable: true,
          },
          {
            label: "订单日期",
            prop: "timeData",
            type: "datetimerange",
            searchRange: true,
            defaultTime:['00:00:00', '23:59:59'],
            format:'yyyy-MM-dd HH:mm:ss',
            valueFormat:'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: "订单日期开始时间",
            endPlaceholder: "订单日期结束时间",
            rules: [
              {
                required: true,
                message: "请选择订单日期段",
                trigger: "blur",
              },
            ],
            hide: true,
            search: true,
            searchSpan: 12,
            display: false,
            overHidden:true,
          },
          {
            label: "服务商编号",
            prop: "serviceNo",
            type: "input",
            hide:true,
            //sortable: true,
            minWidth:150,
            overHidden:true
          },
          {
            label: "订单备注",
            prop: "shopRemarks",
            type: "input",
            hide: false,
            minWidth:150,
            overHidden:true
            //sortable: true,
          },
          {
            label: "审核备注",
            prop: "shopExRemarks",
            type: "textarea",
            hide:true,
            //sortable: true,
          },
          {
            label: "",
            prop: "tenantId",
            type: "input",
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            hide:true,
            viewDisplay: false,
          },
          {
            label: "",
            prop: "createUser",
            type: "input",
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            hide:true,
            viewDisplay: false,
          },
          {
            label: "",
            prop: "createDept",
            type: "input",
            //sortable: true,
            hide:true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },

          {
            label: "",
            prop: "updateUser",
            type: "input",
            hide:true,
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: "",
            prop: "updateTime",
            type: "input",
            hide:true,
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: "",
            prop: "isDeleted",
            type: "input",
            hide:true,
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
          {
            label: "状态",
            prop: "status",
            type: "input",
            hide:true,
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
          },
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [{
          label: '模板上传',
          prop: 'excelFile',
          type: 'upload',
          drag: true,
          loadText: '模板上传中，请稍等',
          span: 24,
          propsHttp: {
            res: 'data'
          },
          tip: '请上传 .xls,.xlsx 标准格式文件',
          action: "/api/rb-oem/shopRefund/shop_refund/import"
        },
        {
          label: '模板下载',
          prop: 'excelTemplate',
          formslot: true,
          span: 24,
        }
        ]
      },
      examineVisible:false,//审核对话框
      // orderId:"",//订单id
      examineData:{
        shopRefundNo:"",
        shopRefundTotal:"",
        shopExRemarks:""
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.shop_refund_add, false),
        viewBtn: this.vaildData(this.permission.shop_refund_view, false),
        delBtn: this.vaildData(this.permission.shop_refund_delete, false),
        editBtn: this.vaildData(this.permission.shop_refund_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },


  watch: {
    "search.timeData"(val){
      if(val){
        this.search.orderBeginTime = val[0];
        this.search.orderEndTime = val[1];
      }else{
        this.search.orderBeginTime = "";
        this.search.orderEndTime = "";
      }
    }
  },
  methods: {
    /* 审核驳回处理 */
    handleReject() {
      this.$confirm("请确认退款审核驳回", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.examineData.shopOrderStatus = "2";
        if(this.examineData.shopExRemarks){
          update(this.examineData).then((res) => {
            if (res.status == "200") {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.examineHandleClose();
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        }else{
          this.$message({
            showClose: true,
            message: '备注内容不能为空！！！',
            type: 'warning'
          });
        }
        
      });
    },
    /* 审核通过处理 */
    handleRefund() {
      this.$confirm("请确认退款审核通过", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.examineData.shopOrderStatus = "3";
        update(this.examineData).then((res) => {
          if (res.status == "200") {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.examineHandleClose();
          } else {
            this.$message({
              type: "error",
              message: res.data.message,
            });
          }
        });
      });
    },
    // 审核对话框，关闭回调
    examineHandleClose(){
      // this.orderId = "";
      this.examineVisible = false;
      this.examineData = {
        shopRefundNo:"",
        shopRefundTotal:"",
        shopExRemarks:""
      } 
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      ShopRefundUnapprovedList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      // 获取统计
      refundStatistics(Object.assign(params, this.query)).then((res) => {
         this.countData = res.data.data;
      });
    }, handleImport() {
      this.excelBox = true;
    },

    handlExamine(row) {
      this.examineVisible = true;
      // this.orderId = row.id;
      this.examineData =  Object.assign(this.examineData, row)
        // this.$router.push({
        // name: "退款审核",
        // query: {
        //   id: row.id,
        // },
      // });

    },

    handleDetail(row) {
        this.$router.push({
        name: "退款订单详情",
        query: {
          id: row.id,
        },
      });

    },
    handleExport() {
      this.$confirm("是否导出退款订单数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        if (this.search.timeData[0]) {
          this.search.orderBeginTime = this.search.timeData[0];
        }
        if (this.search.timeData[1]) {
          this.search.orderEndTime = this.search.timeData[1];
        }

        let params ={
          ...this.search,
          current:'-1',
          size:'-1'
        }
        exportRefundUnapproved(params).then((res) => {
            downloadFileExcel(res);
          },
          (error) => {
            window.console.log(error);
          });
      });
    },
    handleTemplate() {
      window.open(`/api/rb-oem/shopRefund/shop_refund/export-template?${this.website.tokenHeader}=${getToken()}`);
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop
        this.query.descs = ""
      } else {
        //倒序
        this.query.descs = val.prop
        this.query.ascs = ""
      }
      this.refreshChange();
    }
  }
};
</script>

<style>
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;  
}

.redFontBox {
  margin-right: 40px;
  color: red;
}
.dialog-footer{
  display: flex;
  justify-content: center;
  align-content: center;
}
</style>
